import os
import hashlib
import subprocess

def calculate_md5(file_path):
    """ 计算文件的 MD5 哈希值 """
    hash_md5 = hashlib.md5()
    with open(file_path, "rb") as f:
        for chunk in iter(lambda: f.read(4096), b""):
            hash_md5.update(chunk)
    return hash_md5.hexdigest()

def rename_files_with_md5(folder_path):
    """ 遍历文件夹中的所有文件，并将文件名更改为文件的 MD5 哈希值 """
    for filename in os.listdir(folder_path):
        file_path = os.path.join(folder_path, filename)
        if os.path.isfile(file_path):
            # 计算文件的 MD5 哈希值
            md5_value = calculate_md5(file_path)
            # 构建新的文件名
            new_filename = f"{md5_value}{os.path.splitext(filename)[1]}"
            new_file_path = os.path.join(folder_path, new_filename)
            # 重命名文件
            os.rename(file_path, new_file_path)
            print(f"Renamed {file_path} to {new_file_path}")

def doc_to_docx(doc_path, docx_path):
    """ 使用 libreoffice 进行文件转换 """
    try:
        result = subprocess.run(
            ['libreoffice', '--headless', '--convert-to', 'docx', '--outdir', os.path.dirname(docx_path), doc_path],
            stdout=subprocess.PIPE,
            stderr=subprocess.PIPE,
            text=True
        )
        if result.returncode != 0:
            print(f"Error converting {doc_path}: {result.stderr}")
            return False
        return True
    except Exception as e:
        print(f"Error: {e}")
        return False

def convert_docs_to_docx(folder_path):
    """ 遍历文件夹中的所有 .doc 文件，先重命名再转格式 """
    # 首先重命名文件
    rename_files_with_md5(folder_path)

    # 遍历文件夹中的所有 .doc 文件
    for filename in os.listdir(folder_path):
        if filename.endswith('.doc'):
            doc_path = os.path.join(folder_path, filename)
            docx_path = os.path.join(folder_path, filename[:-4] + '.docx')

            # 转换 .doc 文件为 .docx 文件
            if doc_to_docx(doc_path, docx_path):
                # 删除原始的 .doc 文件
                os.remove(doc_path)
                print(f"Converted and deleted {doc_path}")
            else:
                print(f"Failed to convert {doc_path}")

if __name__ == "__main__":
    # 指定要处理的文件夹路径
    folder_path = '/home/user/tmp'
    convert_docs_to_docx(folder_path)
